package com.yuda.tools.authreport.controller;

import cn.hutool.extra.ssh.JschRuntimeException;
import cn.hutool.extra.ssh.JschUtil;
import cn.hutool.extra.ssh.Sftp;
import com.jcraft.jsch.Session;
import com.yuda.tools.authreport.service.AuthReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/pdfDel")
public class DeletePdfOneMonthAgo {

    @Autowired
    private AuthReportService authReportService;


    /**
     * window 端使用 的工具
     * @throws Exception
     */
    @GetMapping
    public void delete() {
        LocalDateTime now = LocalDateTime.now();
        String day = now.getDayOfMonth() < 10 ? "0" + now.getDayOfMonth() : "" + now.getDayOfMonth();
        String time = now.getYear() + "-" + (now.getMonthValue() - 1) + "-" + day;
        List<String> list = authReportService.listStudentsForDeletePdf(time);
        Session session = null;
        Sftp sftp = null;
        try {
            session = JschUtil.getSession("182.92.96.88", 22, "root", "Thussat@200518");
            sftp = JschUtil.createSftp(session);
            System.out.println("session.isConnected() ===  >  " + session.isConnected());
            sftp.cd("/mnt/auth_pdf/");
            for (String s : list) {
                String[] split = s.split(",");
                try {
                    sftp.delFile(split[0] + "/" + split[1] + ".pdf");
                }catch (JschRuntimeException e) {
                    System.out.println("无文件，跳过");
                }
                System.out.println("删除文件： " + split[0] + "/" + split[1] + ".pdf");
            }
        }  finally {
            if (sftp != null) {
                sftp.close();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }
}
